package com.csea.app.service.impl;

import com.csea.app.model.vo.idiom.SearchPublicIdiomReqVO;
import com.csea.app.model.vo.idiom.SearchPublicIdiomRspVO;
import com.csea.app.service.PublicIdiomService;
import com.csea.common.domain.dos.PublicIdiomDo;
import com.csea.common.domain.mapper.PublicIdiomMapper;
import com.csea.common.service.CozeService;
import com.csea.common.utils.Response;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Objects;

@Service
public class PublicIdiomServiceImpl implements PublicIdiomService {
    @Autowired
    private PublicIdiomMapper publicIdiomMapper;
    @Autowired
    private CozeService cozeService;

    /**
     * 根据关键字搜索成语
     */
    @Override
    public Response<List<SearchPublicIdiomRspVO>> searchPublicIdiomByKeyword(SearchPublicIdiomReqVO reqVO) {
        // 查询条件
        String keyword = reqVO.getKeyword();

        // 查询
        List<PublicIdiomDo> publicIdiomDos = publicIdiomMapper.selectByWordLike(keyword);

        // 转换为响应对象
        List<SearchPublicIdiomRspVO> vos = null;
        if (Objects.nonNull(publicIdiomDos)) {
            vos = publicIdiomDos.stream().map(
                    publicIdiomDo -> SearchPublicIdiomRspVO.builder()
                            .idiomId(publicIdiomDo.getIdiomId())
                            .word(publicIdiomDo.getWord())
                            .meaning(publicIdiomDo.getMeaning())
                            .emotionalColor(publicIdiomDo.getEmotionalColor())
                            .synonyms(publicIdiomDo.getSynonyms())
                            .antonyms(publicIdiomDo.getAntonyms())
                            .confusingWordAnalysis(publicIdiomDo.getConfusingWordAnalysis())
                            .examples(publicIdiomDo.getExamples())
                            .build()
            ).toList();
        }

        return Response.success(vos);
    }

    /**
     * 根据关键词搜索成语
     */
    @Override
    public Response<PublicIdiomDo> searchPublicIdiomByCoze(String keyword) {
        // 调用 coze 服务解析成语
        PublicIdiomDo idiomDo = cozeService.parseIdiomByCoze(keyword);

        // 新增：将解析结果写入公共数据库
        if (idiomDo != null) {
            publicIdiomMapper.insert(idiomDo);
        }

        return Response.success(idiomDo);
    }

    /**
     * 根据关键词搜索成语
     */
    @Override
    public boolean searchAndSavePublicIdiomByCoze(String keyword) {
        // 调用 coze 服务解析成语
        PublicIdiomDo idiomDo = cozeService.parseIdiomByCoze(keyword);

        // 新增：将解析结果写入公共数据库
        if (idiomDo != null) {
            int insert = publicIdiomMapper.insert(idiomDo);
            return insert > 0;
        }
        return false;
    }
}
